package net.xxcxcxcx.xc_enhancedmob.packet;

import net.fabricmc.fabric.api.networking.v1.PacketByteBufs;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.network.Packet;
import net.minecraft.network.PacketByteBuf;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.registry.Registry;

import java.util.UUID;

public class CustomEntitySpawnPacket {
    public short velocityX, velocityY, velocityZ;
    public int id, entityData;
    public UUID uuid;
    public EntityType<?> entityType;
    public double x, y, z;
    public byte pitch, yaw;

    public CustomEntitySpawnPacket(PacketByteBuf buf) {
        id = buf.readVarInt();
        uuid = buf.readUuid();
        entityType = Registry.ENTITY_TYPE.get(buf.readVarInt());
        x = buf.readDouble();
        y = buf.readDouble();
        z = buf.readDouble();
        pitch = buf.readByte();
        yaw = buf.readByte();
        entityData = buf.readInt();
        velocityX = buf.readShort();
        velocityY = buf.readShort();
        velocityZ = buf.readShort();
    }

    public static Packet<?> creat(Entity entity, Identifier identifier) {
        return creat(entity, 0, identifier);
    }

    public static Packet<?> creat(Entity entity, int entityData, Identifier identifier) {
        return creat(entity.getEntityId(), entity.getUuid(), entity.getX(), entity.getY(), entity.getZ(), entity.pitch, entity.yaw, entity.getType(), entityData, entity.getVelocity(), identifier);
    }

    public static Packet<?> creat(Entity entity, EntityType<?> entityType, int data, BlockPos pos, Identifier identifier) {
        return creat(entity.getEntityId(), entity.getUuid(), pos.getX(), pos.getY(), pos.getZ(), entity.pitch, entity.yaw, entityType, data, entity.getVelocity(), identifier);
    }

    public static Packet<?> creat(int id, UUID uuid, double x, double y, double z, float pitch, float yaw, EntityType<?> entityTypeId, int entityData, Vec3d velocity, Identifier identifier) {
        PacketByteBuf buf = PacketByteBufs.create();
        buf.writeVarInt(id);
        buf.writeUuid(uuid);
        buf.writeVarInt(Registry.ENTITY_TYPE.getRawId(entityTypeId));
        buf.writeDouble(x);
        buf.writeDouble(y);
        buf.writeDouble(z);
        buf.writeByte(MathHelper.floor(pitch * 256.0f / 360.0f));
        buf.writeByte(MathHelper.floor(yaw * 256.0f / 360.0f));
        buf.writeInt(entityData);
        buf.writeShort((int) (MathHelper.clamp(velocity.x, -3.9, 3.9) * 8000.0));
        buf.writeShort((int) (MathHelper.clamp(velocity.y, -3.9, 3.9) * 8000.0));
        buf.writeShort((int) (MathHelper.clamp(velocity.z, -3.9, 3.9) * 8000.0));
        return ServerPlayNetworking.createS2CPacket(identifier, buf);
    }
}
